package cn.newstrength.cuichao.step;

import cn.newstrength.cuichao.data.CuichaoObj;
import cn.newstrength.wtdf.plugin.service.RedisService;
import cn.newstrength.wtdf.plugin.util.TranUtils;
import cn.newstrength.wtdf.web.databus.DataContext;
import cn.newstrength.wtdf.web.exception.PAIException;
import cn.newstrength.wtdf.web.processor.Operation;
import cn.newstrength.wtdf.web.processor.OperationStep;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.util.Map;

public class RedisCuichaoStep implements OperationStep {
    private final static Logger logger = LoggerFactory.getLogger(RedisCuichaoStep.class);
    @Override
    public int excute(Operation oper) throws PAIException {
        /*
         * 数据预处理
         */
        DataContext dc = oper.getContext();
        String key = dc.getElementValue("key");
        /*
         * 获取 Redis 服务
         */
        RedisService redisService = oper.getBean("redisService", RedisService.class);
        /*
         * 存储字符串
         */
        redisService.put("cn:newstrength:nsms.cuichao.string", "Hi redis!",30);
        logger.info("Redis value：{}", TranUtils.toJson(redisService.get("cn:newstrength:nsms.cuichao.string")));
        /*
         * 存储对象
         */
        CuichaoObj cuichaoObj = new CuichaoObj();
        cuichaoObj.setId(1);
        cuichaoObj.setName("崔超");
        cuichaoObj.setGender("1");
        cuichaoObj.setPassword("changeit");
        cuichaoObj.setAge(40);
        redisService.put("cn:newstrength:nsms.cuichao.bean", cuichaoObj,30);//30秒后删除
        Object value = redisService.get("cn:newstrength:nsms.cuichao.bean");
        logger.info("Redis value：{}",TranUtils.toJson(value));
        /*
         * 存储文件
         */
        File file = new File("c:/Windows/system.ini");
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(file);
            byte[] array = IOUtils.toByteArray(fs);
            redisService.put("cn:newstrength:nsms.cuichao.file", array,30);//30秒后删除
        } catch (Exception e) {
            logger.error("文件不存在");
        } finally {
            IOUtils.closeQuietly(fs);
        }
        /*
         * 回传数据
         */
        dc.setTranStepResult("存储字符串、cuichaoObj对象，File对象成功，请查看节点 cn:newstrength:nsms.cuichao （TTL 30S）");
        return 0;
    }

    @Override
    public int init(Map<String, String> map) {
        return 0;
    }
}
